<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AAlert>需要注意一下采购单与出入库存的数据</AAlert>
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ACard
            v-for="(item, index) in form.materialReqList"
            :key="index"
            class="card-container"
            size="small"
          >
            <template #extra>
              <ALink @click="editProduct('add')">增加材料</ALink>
              <ALink v-if="form.materialReqList.length > 1" @click="editProduct('del', index)">
                删除材料
              </ALink>
            </template>
            <ARow :gutter="10">
              <ACol :span="12">
                <AFormItem
                  :field="`materialReqList[${index}].materialStockId`"
                  label="产品"
                  :rules="[{ required: true, message: '请选择产品' }]"
                  :validate-trigger="['change', 'blur']"
                >
                  <ASelect
                    v-model="item.materialStockId"
                    v-model:input-value="productSearch"
                    allow-search
                    placeholder="请选择产品名称"
                    :trigger-props="{ contentStyle: { width: 'max-content' } }"
                    :filter-option="proFilter"
                    @change="changeEvent('material', item)"
                  >
                    <template #empty>
                      <div style="padding: 6px 12px">
                        <ALink :hoverable="false" @click="openAdd()"> 新增产品 </ALink>
                      </div>
                    </template>
                    <AOption
                      v-for="(item, index) in stockList"
                      :key="index"
                      :label="item.materialName"
                      :value="`${item.materialStockId}-${item.spec}`"
                      :disabled="detailIds.includes(`${item.materialStockId}-${item.spec}`)"
                    >
                      <div class="w100 erp-row-center-between">
                        <div>{{ item.materialName }}</div>
                        <ATag v-if="item.spec" color="blue">
                          {{ item.spec }}
                        </ATag>
                      </div>
                    </AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="spec" label="规格">
                  {{ item.spec }}
                </AFormItem>
              </ACol>
              <ACol :span="6">
                <AFormItem field="unit" label="单位">
                  {{ item.unit }}
                </AFormItem>
              </ACol>
              <ACol :span="6">
                <AFormItem field="materialCategory" label="类别">
                  {{ item.materialCategory }}
                </AFormItem>
              </ACol>

              <ACol :span="12">
                <AFormItem field="inboundQty" label="入库数量">
                  <AInputNumber
                    v-model="item.inboundQty"
                    model-event="input"
                    placeholder="请输入入库数量"
                  />
                </AFormItem>
              </ACol>
            </ARow>
          </ACard>
        </AForm>
      </AScrollbar>
    </AModal>
    <addStock
      v-model:visible="addProductVisible"
      title="新增原材料"
      :check-data="{ materialName: productSearch }"
      @reload="getProductList"
    ></addStock>
  </div>
</template>

<script lang="ts" setup>
import { Message, SelectOptionData } from '@arco-design/web-vue'
import addStock from '@renderer/views/warehouseManage/Inventory/finished/editPopupForm.vue'
import { getSupplierAllList, SupplierResItem } from '@renderer/api/company'
import {
  batchAddStockRecord,
  getStockAllList,
  StockRecordReq,
  StockResItem
} from '@renderer/api/warehouseManage'
import { useMenuState } from '@renderer/store'

const emit = defineEmits(['update:visible', 'reload'])
const formRef = ref()
const supplierList = ref<SupplierResItem[]>([])
const menuParam = useMenuState()
const productSearch = ref('')
const addProductVisible = ref(false)
const detailIds = computed(() => form.value.materialReqList.map((item) => item.materialStockId))
const form = ref<{ materialReqList: StockRecordReq[] }>({
  materialReqList: [
    {
      inboundQty: 0
    }
  ]
})

// 获取供应商列表
const getCompanyList = () => {
  getSupplierAllList({ supplierName: '' }).then((res) => {
    supplierList.value = res.data.list
  })
}
const stockList = ref<StockResItem[]>([])
// 获取产品列表
const getProductList = () => {
  getStockAllList({ materialName: '', materialType: 2 }).then((res) => {
    stockList.value = res.data.list
  })
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 新增
          form.value.materialReqList = form.value.materialReqList.map((item) => {
            item.stockRecordId = undefined
            item.formType = 0
            item.materialType = 2
            item.materialStockId = item.materialStockId?.split('-')[0]
            return item
          })
          batchAddStockRecord(form.value.materialReqList).then(() => {
            Message.success('新增成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value.materialReqList = [
        {
          inboundQty: 0
        }
      ]
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getCompanyList()
      getProductList()
      break
    case 'cancel':
      formRef.value.resetFields()
      menuParam.switchEditStatus(false)
      emit('update:visible', false)
      break

    default:
      break
  }
}

// 新增产品
const openAdd = () => {
  addProductVisible.value = true
}

const changeEvent = (type: string, params: StockRecordReq) => {
  switch (type) {
    case 'material':
      {
        const temp = stockList.value.find(
          (item) => `${item.materialStockId}-${item.spec}` === params.materialStockId
        )
        if (temp) {
          params.materialCategory = temp.materialCategory
          params.spec = temp.spec
          params.materialCode = temp.materialCode
          params.materialDesc = temp.materialDesc
          params.fluteType = temp.fluteType
          params.boxSpec = temp.boxSpec
          params.crimpLine = temp.crimpLine
          params.unit = temp.unit
        }
      }
      break

    default:
      break
  }
}

const editProduct = (type: 'add' | 'del', index?: number) => {
  switch (type) {
    case 'add':
      form.value.materialReqList.push({
        inboundQty: 0
      })
      break
    case 'del':
      form.value.materialReqList.splice(index!, 1)
      break

    default:
      break
  }
}

const proFilter = (inputValue: string, option: SelectOptionData) => {
  return (
    (option.value as string).split('-')[1].includes(inputValue) ||
    (option.label as string).includes(inputValue)
  )
}
</script>
<style scoped lang="less">
:deep(.arco-select-option-content) {
  width: 100%;
}
.card-container + .card-container {
  margin-top: 10px;
}
</style>
